package splash.core.connection;

import java.text.ParseException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/*
    Name value
    Value should be URL Encoded
    
    -Check security once again-
*/

public class Property
{
    private String name;
    private String value;

    public Property(String name, String value)
    {
	if(name.matches("\\W"))
		throw new IllegalArgumentException("Non-word characters: " + name);
	    
	this.name = name;
        this.value = value;
    }
    
    private Property()
    {
    }
    
    public static Property parseProperty(String up) throws ParseException
    {
	if(!up.matches("^\\w+ [\\w\\.%/\\*\\-\\+:=&\\?]+$"))
	  throw new ParseException("String not valid: " + up, 0);
	
	String[] s = up.split(" ");
        try
        {
            return new Property(s[0], URLDecoder.decode(s[1],"UTF-8"));
        }
        catch(Exception e)
        {
            e.printStackTrace();
            throw new ParseException("Napaka pri parsanju", 0);
        }
    }
    
    public String getName()
    {
	return this.name;
    }
    
    public String getValue()
    {
	return this.value;
    }
    
    public void setName(String name)
    {
	if(!value.matches("^\\w$"))
		throw new IllegalArgumentException("It can onnly contains word characters.");
	
	this.name = name;
    }
    
    public void setValue(String value)
    {
        try{
            if(!value.matches("^[\\w\\.%/\\*\\-\\+:=&\\?]+$"))
		this.value = URLEncoder.encode(value, "UTF-8");
	else
		this.value = value;
        }
        catch(Exception e){}
	
    }
    
    public String generateString()
    {
	    return name + " " + value;
    }
    
}